import {useEffect, useReducer} from 'react';
import { reducer,initialState } from './store/reducer';
import axios from 'axios';
import './App.css';
import Movie from './comonpents/Movie';
import Search from './comonpents/Search'
import spinner from './assets/ajax-loader.gif';
// console.log(spinner);
const App = ()=>{

  // 与中央数据 store 联系
  // useReducer
  // useEffect api
  // loading, 全局状态
  // movies 
  // 1. 联系中央  不只管理数据，还有数据的流向和修改
  // 2. state 在某一个时刻是既定的 动态的
  // 对中央数据的读操作，dispatch

  const [state,dispatch]=useReducer(reducer,initialState);
  const {loading,movies,errorMessage}=state;
  // console.log(state,dispatch);

  // state.loading=false;
  useEffect(()=>{
    // console.log('loading');
    axios.get('https://www.omdbapi.com/?s=man&apikey=4a3b711b')
    .then(res=>{
      // console.log(res);
      let payload=res.data.Search;
      dispatch({type:'search_movies_success',payload}
      )

    });
  },[])
  // 住件函数，必须返回 JSX
  // 可以把HTML（xml）在js里写出来

  const search=searchValue=>{
    axios.get(`https://www.omdbapi.com/?s=${searchValue}&apikey=4a3b711b`)
    .then(res=>{
      // console.log(res);
      if(res.data.Error){
        dispatch({
          type:'error'
        })
        return ;
      }
      let payload=res.data.Search;
      dispatch({
        type:'search_movies_success',
        payload
      },[])
    })
  }

  return (
    <div className="App">
      <Search search={search} />
      {loading?<img src={spinner} className="spinner" alt="loding spinner" />:''}
      {!errorMessage?
        <div className="movies">
          {
          movies.map(movie=><Movie movie={movie}  key={movie.imdbID}/>)
          }
        </div>
      :<p>没有找到电影</p>
      }
    </div>
  )
}
export default App;